package admin.data;

import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.PageModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

public class PageData {
	private Objectify ofy;
	
	private Cache cache = null;
	
	public PageData() {
		try {
			ObjectifyService.register(PageModel.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public PageModel getConfig(String id) {
		PageModel page = new PageModel();
		if (cache != null && cache.containsKey(id)) {
			page = (PageModel) cache.get(id);
		} else {
			try {
				page = ofy.get(new Key<PageModel>(PageModel.class, id));
				cache.put(id, page);
			} catch (Exception e) {
				page = null;
			}
		}
		return page;
	}
	
	public void insert(PageModel page) {
		if (cache != null) {
			cache.put(page.getId(), page);
		}
		ofy.put(page);
	}
	
	public void delete(PageModel page) {
		if (cache != null && cache.containsKey(page.getId())) {
			cache.remove(page.getId());
		}
		ofy.delete(page);
	}
}
